package com.smm.web.mtower.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smm.web.mtower.bo.OrderBO;
import com.smm.web.mtower.domain.JsonReturn;
import com.smm.web.mtower.domain.RemoteOrder;
import com.smm.web.mtower.domain.SnapOrder;
import com.smm.web.mtower.util.LocationUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;


/**
 * Created by zhenghao on 2016/6/15.
 *
 */
@Controller
@RequestMapping("/remote")
public class RemoteController {

    private static final Logger logger= Logger.getLogger(RemoteController.class);


    @Resource
    private OrderBO orderBO;


    @RequestMapping("/order")
    @ResponseBody
    public JsonReturn reciveOrder(HttpServletRequest request,HttpServletResponse response){

        //order demo: order={'code':'01','camera':{'ip':'192.168.8.250','port':'8000','account':'admin','password':'abc12345'}}

        String order = request.getParameter("order");

        logger.info("parameter order:"+order);

        try{

            if(order==null || order.trim().equals("")) throw new Exception("order is null");

            //解析指令
            JSONObject jsonObj = JSON.parseObject(order);

            String code = jsonObj.getString("code");

            logger.info("code:"+code);

            //如果是抓拍指令
            if(code.equals(RemoteOrder.Order_Snap)){

                SnapOrder sorder = JSON.parseObject(order,SnapOrder.class);

                //执行抓拍，返回图片保存物理路径
                String imageFullPath = orderBO.snap(sorder);

                //回传图片给服务器
                returnImage(response,imageFullPath);

                //回传完成，删除图片
                File  file = new File(imageFullPath);
                file.delete();

                return new JsonReturn(true,"OK",null);
            }

            //如果是获取位置指令
            if(code.equals(RemoteOrder.Order_Location)){

                return new JsonReturn(true,"OK", LocationUtil.getIPXY());
            }


            //如果没有匹配指令，抛出异常
            throw new Exception("no match order code");

        }catch (Exception e){

            e.printStackTrace();

            return new JsonReturn(false,e.getMessage(),null);
        }


    }

    private void returnImage(HttpServletResponse response, String imageFullPath) throws Exception {

        //创建file对象
        File file=new File(imageFullPath);

        //设置response的编码方式
        response.setContentType("application/x-msdownload");

        //写明要下载的文件的大小
        response.setContentLength((int)file.length());

        //设置附加文件名
        response.setHeader("Content-Disposition","attachment;filename="+new String(file.getName().getBytes("UTF-8"),"UTF-8"));

        //读出文件到i/o流
        FileInputStream fis=new FileInputStream(file);
        BufferedInputStream buff=new BufferedInputStream(fis);

        byte [] b=new byte[1024];//相当于我们的缓存

        long k=0;//该值用于计算当前实际下载了多少字节

        //从response对象中得到输出流,准备下载
        OutputStream myout=response.getOutputStream();

        //开始循环下载

        while(k<file.length()){

            int j=buff.read(b,0,1024);
            k+=j;

            //将b中的数据写到客户端的内存
            myout.write(b,0,j);

        }

        //将写入到客户端的内存的数据,刷新到磁盘
        myout.flush();

        //关闭流
        myout.close();

        buff.close();

        fis.close();

    }


}
